package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 接受自动补货工单消息
 * 创建补货工单
 */
@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class VmsSupplyTaskHandler implements MsgHandler {
    @Autowired
    private VMService vmService;
    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //1. json转成对象
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        //获取售货机信息
        VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());
        //获取指定区域的工单分数最少的运维人员的id
        Integer leastUser = taskService.getLeastUser(vmInfo.getRegionId(), Boolean.TRUE);
        //开始创建补货工单
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setCreateType(VMSystem.AUTO_CREATE_TYPE);
        taskViewModel.setInnerCode(vmInfo.getInnerCode());
        taskViewModel.setUserId(leastUser);
        taskViewModel.setAssignorId(VMSystem.SYSTEM_AUTO_CREATE);
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        List<TaskDetailsViewModel> details = new ArrayList();
        for (SupplyChannel channel : supplyContract.getSupplyData()) {
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            taskDetailsViewModel.setChannelCode(channel.getChannelId());
            taskDetailsViewModel.setExpectCapacity(channel.getCapacity());
            taskDetailsViewModel.setSkuId(channel.getSkuId());
            taskDetailsViewModel.setSkuName(channel.getSkuName());
            taskDetailsViewModel.setSkuImage(channel.getSkuImage());
            details.add(taskDetailsViewModel);
        }
        taskViewModel.setDetails(details);
        taskService.createTask(taskViewModel);

    }
}
